#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/5/25 17:02
# @Author : wn 
# @File: channel.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡

from django.shortcuts import render, HttpResponse, redirect
from Manager.models import *
from Rbac.models import *
from Manager.views.service import my_page
from django.http import JsonResponse
import json
from Django_Admin.enumType import *
from Rbac.utils.encrypt import encryptPassword
from Rbac.utils.login_deco import *


@auth
def channel_list(request):
    # 当前在第几页
    off = request.GET.get('offset', None)
    # 一页几条数据
    lim = request.GET.get('limit', None)
    # 获取url后拼接的search
    search = request.GET.get('search', None)
    # 判断url后面是否拼接了search，没有，返回页面；有显示搜索条件的值
    if search is None:
        return render(request, 'channel.html')
    else:
        # 按搜索条件获取值
        if search:
            channel_list = Channel.objects.values().filter(channelid__contains=search)
        else:
            channel_list = Channel.objects.values()
        # 把queryset转成列表[{},{}]
        channel_list = list(channel_list)
        for item in channel_list:
            item['option'] = item['channelid']
            # 枚举值
            item['apitype'] = ApiType_choices.get(item['apitype'], None),
            item['terminaltype'] = TerminalType_choices.get(item['terminaltype'], None),
            item['isactive'] = IsActive_choices.get(item['isactive'], None),
            item['loglevel'] = LogLevel_choices.get(item['loglevel'], None),
        result = my_page(channel_list, lim, off)
        return JsonResponse(result, safe=False)


# 添加，修改，删除
def channel_modify(request):
    ##拿到登录用户id
    userid = request.session["id"]
    isdelete = Customer.objects.filter(customerid=userid).filter(roles__permissions__url__endswith='channel_list(delete)')
    ismodify = Customer.objects.filter(customerid=userid).filter(roles__permissions__url__endswith='channel_list(modify)')
    isadd = Customer.objects.filter(customerid=userid).filter(roles__permissions__url__endswith='channel_list(add)')
    if request.method == 'GET':
        # channelid:主键名
        channel_id = request.GET['channelid']
        item = Channel.objects.values().filter(channelid=channel_id).first()
        # print('被修改的值：', item)
        if item:
            return JsonResponse(item, safe=False)
    else:
        if request.POST.get('delete', None):
            if isdelete:
                # 删除
                channelid = request.POST.get('id')
                tdchannel = Customerchannelrel.objects.filter(tdchannelid=channelid).exists()
                mdchannel = Customerchannelrel.objects.filter(mdchannelid=channelid).exists()
                delete_msg = ""
                if tdchannel | mdchannel:  # 如果有一个有，那就说明分账户存在，然后把删除信息填进去
                    delete_msg = "请先删除对应的分账号信息！"
                    return HttpResponse(delete_msg)
                else:
                    Channel.objects.filter(channelid=channelid).delete()
                    return HttpResponse('y')
            else:
                return HttpResponse('该用户无操作权限')
        else:
            try:
                data = request.POST
                # 读取扩展信息配置文件
                # print(data['apitype'][0])
                '''
                因为extendinfo发送的post携带数据格式和修改删除提交的post数据格式不同，
                所以这个地方加一个try,如果抛异常证明是提交的post请求,否则是extend的post
                '''
                try:
                    if data['flag'] == "extendinfo":
                        apitype = data['apitype'][0]
                        terminaltype = data.get("terminaltype") if data.get("terminaltype") else ""
                        filename = ''
                        if apitype == '1':
                            filename = 'config_ctp'
                        if apitype == '3':
                            filename = 'config_femas'
                        if apitype == '4':
                            filename = 'config_sim'
                        if apitype == '5':
                            filename = 'config_ufx'
                        if apitype == '6' and terminaltype == '1':
                            filename = 'config_cfets_trade'
                        if apitype == '6' and terminaltype == '2':
                            filename = 'config_cfets_market'
                        if apitype == '7':
                            filename = 'config_SIP'
                        if apitype == '8':
                            filename = 'config_Cfets_xQuant'
                        if apitype == '9':
                            filename = 'config_MDCenter'
                        if apitype == 'a':
                            filename = 'QBMDApi'
                        from Manager.utils.ReadCsv import ReadCsv
                        ei = ''
                        if filename != '':
                            # 扩展信息的值
                            ei = ReadCsv(filename).values()
                            # print(ei)
                            # print(type(ei))
                            return HttpResponse(ei)
                        else:
                            return HttpResponse("")
                    # print(data)
                except:
                    # 对用户代码做监听，加一个try，因为
                    # 这两个post请求（判断用户代码是否唯一、提交新建或修改请求）的数据格式不同，所以会抛异常
                    try:
                        if data['chnelid']:
                            cid_count = Channel.objects.filter(channelid=data['chnelid']).count()
                            if cid_count >= 1:
                                # 如果channelid已存在，提示已存在，不允许添加
                                return HttpResponse('q')
                    except:
                        if Channel.objects.filter(channelid=json.loads(data['channelid'])[0]).count() >= 1:
                            if ismodify:
                                # 修改
                                if json.loads(data['ismd5'])[0] == False:
                                    Channel.objects.filter(channelid=json.loads(data['channelid'])[0]).update(
                                        apitype=json.loads(data["apitype"])[0],
                                        terminaltype=json.loads(data["terminaltype"])[0],
                                        userid=json.loads(data['userid'])[0],
                                        password=encryptPassword(json.loads(data['password'])[0]),
                                        addresslist=json.loads(data['addresslist'])[0],
                                        closetimepoint=json.loads(data['closetimepoint'])[0],
                                        loglevel=json.loads(data['loglevel'])[0],
                                        extendinfo=json.loads(data['extendinfo'])[0],
                                        isactive=json.loads(data['isactive'])[0],
                                    )
                                else:
                                    Channel.objects.filter(channelid=json.loads(data['channelid'])[0]).update(
                                        apitype=json.loads(data["apitype"])[0],
                                        terminaltype=json.loads(data["terminaltype"])[0],
                                        userid=json.loads(data['userid'])[0],
                                        password=json.loads(data['password'])[0],
                                        addresslist=json.loads(data['addresslist'])[0],
                                        closetimepoint=json.loads(data['closetimepoint'])[0],
                                        loglevel=json.loads(data['loglevel'])[0],
                                        extendinfo=json.loads(data['extendinfo'])[0],
                                        isactive=json.loads(data['isactive'])[0],
                                    )
                                return HttpResponse('y')
                            else:
                                return HttpResponse("该用户无操作权限！")
                        else:
                            if isadd:
                                # 新增
                                channelid = json.loads(data['channelid'])[0],

                                if json.loads(data['ismd5'])[0] == False:
                                    # 未勾选已加密，加密
                                    Channel.objects.create(
                                        channelid=json.loads(data['channelid'])[0],
                                        apitype=json.loads(data["apitype"])[0],
                                        terminaltype=json.loads(data["terminaltype"])[0],
                                        userid=json.loads(data['userid'])[0],
                                        password=encryptPassword(json.loads(data['password'])[0]),
                                        addresslist=json.loads(data['addresslist'])[0],
                                        closetimepoint=json.loads(data['closetimepoint'])[0],
                                        loglevel=json.loads(data['loglevel'])[0],
                                        extendinfo=json.loads(data['extendinfo'])[0],
                                        # extendinfo=ei,
                                        isactive=json.loads(data['isactive'])[0],
                                    )
                                else:
                                    Channel.objects.create(
                                        channelid=json.loads(data['channelid'])[0],
                                        apitype=json.loads(data["apitype"])[0],
                                        terminaltype=json.loads(data["terminaltype"])[0],
                                        userid=json.loads(data['userid'])[0],
                                        password=json.loads(data['password'])[0],
                                        addresslist=json.loads(data['addresslist'])[0],
                                        closetimepoint=json.loads(data['closetimepoint'])[0],
                                        loglevel=json.loads(data['loglevel'])[0],
                                        extendinfo=json.loads(data['extendinfo'])[0],
                                        # extendinfo=ei,
                                        isactive=json.loads(data['isactive'])[0],
                                    )
                                return HttpResponse('y')
                            else:
                                return HttpResponse("该用户无操作权限！")
            except Exception as e:
                # print(e)
                return HttpResponse(e)

        return render(request, 'channel.html')
